//
//  HSTabBarController.swift
//  Home_school_晓林
//
//  Created by 张晓林 on 16/9/10.
//  Copyright © 2016年 张晓林. All rights reserved.
//

import UIKit

class HSTabBarController: UITabBarController {
    /// 左边按钮的回调闭包
    var leftBtnBlock:(() -> ())?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 设置UI
        setupUI()
        
    }
    
    /// 左边按钮的点击事件
    @objc fileprivate func leftBtnClicked() {
        // 执行闭包，回调事件
        leftBtnBlock?()
    }
}

// MARK: - 设置UI
extension HSTabBarController {
    
    /// 添加所以子控制器
    fileprivate func setupUI() {
        // 设置背景色
        view.backgroundColor = UIColor.orange
        
        let tabDict = [["vc":"HSMessageController","title":"消息","imageName":"inform"],
                       ["vc":"HSHomeworkController","title":"作业","imageName":"homework"],
                       ["vc":"HSClassroomController","title":"课堂","imageName":"class_exercise"],
                       ["vc":"HSScoreController","title":"成绩","imageName":"examination"]]
        
        // 添加子控制器
        for dict in tabDict {
            addController(dict)
        }
    }
    
    /// 重载系统标签控制器的添加子控制器方法
    fileprivate func addController(_ tabInfo:[String:String]) {
        
        // 从info.plist中自动获得命名空间
        guard let bundleName = Bundle.bundleName(),
            let vcName = tabInfo["vc"],
            let imageName = tabInfo["imageName"],
            // 使用反射机制获得控制器类型
            let cls = NSClassFromString("\(bundleName).\(vcName)")
                as? UIViewController.Type else {
                    // 如果为空就返回
                    return
        }
        
        // 初始化控制器
        let vc = cls.init()
        // 设置标签按钮标题和控制器标题
        vc.title = tabInfo["title"]
        // 设置图片
        vc.tabBarItem.image = UIImage(named: "\(imageName)_nor")
        vc.tabBarItem.selectedImage = UIImage(named: "\(imageName)_press")?
            .withRenderingMode(.alwaysOriginal)
        // 设置标签标题字体大小
        vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName:
            UIFont.systemFont(ofSize: 14)],for: UIControlState())
        // 设置标签标题选择颜色
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:
            UIColor.xl_colorWithHex(0x00a0e9)], for: .selected)
        // 添加导航控制器
        let navVc = HSNavViewController(rootViewController: vc)
        // 将设置好的子控制器添加到标签控制器中
        addChildViewController(navVc)
        
        // 添加左边导航按钮
        vc.navigationItem.leftBarButtonItem =
            UIBarButtonItem(image: "icon_menu_nor",
                            HLImage: "icon_menu_press",
                            target: self,
                            action: #selector(leftBtnClicked))
    }
}










